﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Security.Cryptography;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using Lswweb.IDAL;
using Lswweb.Model;
using Lswweb.Common;

namespace Lswweb.Domain
{
    /// <summary>
    /// 用户综合方法
    /// </summary>
    public class Users
    {
        protected readonly static IUsers users = DALFactory.CreateUsers();
        
        #region 获取会员信息

        /// <summary>
        /// 取得当前登录用户
        /// </summary>
        /// <returns></returns>
        public static UserInfo GetUser(int userId)
        {
            return users.GetUser(userId);
        }
        public static UserInfo GetUser(string loginName)
        {
            return users.GetUser(loginName);
        }

        public static IList<UserInfo> GetUsers(string searchKey, RoleType roleType,int pageSize, int pageIndex, out int record)
        {
            return users.GetUsers(searchKey, StatusType.Enabled,roleType, pageSize, pageIndex, out record);
        }

        #endregion

        /// <summary>
        /// 添加新成员信息
        /// </summary>
        /// <param name="membership">成员信息</param>
        public static void AddUser(UserInfo userInfo)
        {
            if (userInfo != null)
            {
                if (users.IsHas(0, userInfo.LoginName))
                {
                    SiteContext.RenderMessage(ExceptionType.UserNameExists);
                }
                else
                {
                    string psw = userInfo.Password;
                    userInfo.Password = Globals.MD5(userInfo.Password);
                    if (users.Insert(userInfo) > 0)
                    {
                        userInfo.Password = psw;
                        Email.SendMail(userInfo);

                        if (!SiteContext.Current.Context.User.Identity.IsAuthenticated)
                        {
                            UserSecurity.Login(userInfo.LoginName,userInfo.Password);
                        }
                        else
                        {
                            SiteContext.RenderMessage(ExceptionType.UserRegisterSuccess);
                        }
                    }
                    else
                        SiteContext.RenderMessage(ExceptionType.UnknownError);
                }
            }
            else
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
            }
        }

        public static bool UserIsVip(int  userId)
        {
            return Orders.GetBuyTotalMoney(userId, new Pair<DateTime?>(null, null)) >= SiteSettings.Settings.VipIntegral;
        }

        /// <summary>
        /// 删除会员信息
        /// </summary>
        /// <param name="userId">会员Id</param>
        public static void Delete(int userId)
        {
            if (userId <= 0)
                SiteContext.RenderMessage(ExceptionType.UserNotFound, SiteContext.Current.ReferrerUrl);

            if( users.Delete(userId))
                SiteContext.RenderMessage(ExceptionType.HandleSuccess,SiteContext.Current.ReferrerUrl);
            else
                SiteContext.RenderMessage(ExceptionType.UnknownError, SiteContext.Current.ReferrerUrl);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="password">新密码</param>
        public static bool ChangePassword(int userId,string password)
        {
            return users.UpdatePsw(userId, Globals.MD5(password));
        }

        /// <summary>
        /// 验证当前注册的用户是否已经存在。
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="userName">用户名</param>
        /// <returns>用户已经存在返回true，用户不存在返回false</returns>
        public static bool IsHas(int userId,string userName)
        {
            //需要验证用户名是否为系统保留关键字不充许注册。
            bool isHas = true;
            if(isHas)
                isHas=users.IsHas(userId,userName);
            return isHas;
        }

        #region profile

        /// <summary>
        /// 修改用户资料
        /// </summary>
        /// <param name="userProfile"></param>
        public static void UpdateProfile(UserProfileInfo userProfile)
        {
            if (userProfile.UserId == SiteContext.Current.User.Id || SiteContext.Current.User.IsAdmin)
            {
                if (users.UpdateProfile(userProfile))
                {
                    if (userProfile.UserId == SiteContext.Current.User.Id)
                        SiteContext.Current.User.Profile = userProfile;

                    SiteContext.RenderMessage(ExceptionType.UserProfileUpdated);
                }
                else
                {
                    SiteContext.RenderMessage(ExceptionType.UnknownError);
                }
            }
            else
            {
                SiteContext.RenderMessage(ExceptionType.AdministrationAccessDenied);
            }
        }

        #endregion

        #region 权限部分

        /// <summary>
        /// 取得会员管理员权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetAaminPowers(int userId)
        {
            return users.GetAdminPowers(userId);
        }

        /// <summary>
        /// 配置用户是否为管理员
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="isAdmin">是否为管理员</param>
        public static void SetUserIsAdmin(string userName, bool isAdmin)
        {
            if (users.IsHas(0, userName))
            {
                if (users.UpdateIsAdmin(userName, isAdmin))
                    SiteContext.RenderMessage(ExceptionType.HandleSuccess);
                else
                    SiteContext.RenderMessage(ExceptionType.UnknownError);
            }
            else
            {
                SiteContext.RenderMessage(ExceptionType.UserNotFound);
            }
        }

        /// <summary>
        /// 配置会员的管理员权限
        /// </summary>
        /// <param name="userId">会员Id</param>
        /// <param name="userAdminPowers">会员权限字符串组，注意多个权限之间用“|”隔开</param>
        public static void SetAdminPowers(int userId, string adminPowers)
        {
            if (userId <= 0)
            {
                SiteContext.RenderMessage(ExceptionType.UserNotFound);
                return;
            }

            bool label = users.UpdateAdminPowers(userId, adminPowers);
            SiteContext.RenderMessage(label ? ExceptionType.UserAdminPowersUpdated : ExceptionType.UnknownError);
        }

        public static bool ValidatePower(string powerName)
        {
            if (SiteContext.Current.User == null)
                return false;

            return SiteContext.Current.User.AdminPowers == "*" ? true : SiteContext.Current.User.AdminPowers.Contains(powerName);
        }
        public static bool ValidatePower()
        {
            return ValidatePower(SiteContext.Current.MapNode.Name);
        }

        #endregion

        #region 取回密码

        /// <summary>
        /// 根据用户名生成用户取回密码的url
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>取回密码url</returns>
        public static string CreateGetPasswordUrl(string userName)
        {
            UserInfo info = GetUser(userName);
            return CreateGetPasswordUrl(info.Id, info.LoginName, info.PasswordAnswer);
        }
        public static string CreateGetPasswordUrl(int userId, string userName, string passwordAnswer)
        {
            string url = SiteSettings.Settings.SiteDomain + SiteUrls.Urls.UserChangePassword();
            string key = DateTime.Now.ToString() + "|" + userId.ToString().ToMD5() + "|" + passwordAnswer.ToMD5();
            string parameter = SiteContext.Current.Context.Server.UrlEncode(key.Encrypt());

            if (url.IndexOf('?') == -1)
                return url + "?AutoGetPassword=" + parameter;
            else
                return url + "&AutoGetPassword=" + parameter;
        }

        /// <summary>
        /// 验证当前url是否有效的取得密码url
        /// </summary>
        /// <param name="id">要取得密码用户的Id</param>
        /// <returns>是否有效</returns>
        public static bool ValidateGetPasswordUrl(int userId, string userName, string passwordAnswer)
        {
            UserInfo info = GetUser(userName);

            if (userId <= 0 || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passwordAnswer))
                throw new Exception("必须配置userId、userName、passwordAnswer三个参数。");

            string query = HttpContext.Current.Request.QueryString["AutoGetPassword"];
            if (query == null || string.IsNullOrEmpty(query) || info == null)
                return false;

            try
            {
                string[] parameters = query.Decrypt().HtmlDecode(SiteContext.Current.Context.Server).Split('|');
                if (parameters[2] == passwordAnswer.ToMD5() && parameters[1] == userId.ToString().ToMD5() && DateTime.Parse(parameters[0]).AddDays(1) > DateTime.Now)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
        public static void ValidateGetPasswordUrl()
        {
            string query = HttpContext.Current.Request.QueryString["AutoGetPassword"];
            if (query == null || string.IsNullOrEmpty(query))
            {
                SiteContext.RenderMessage(ExceptionType.PageNotFond, SiteUrls.Urls.Home);
                return;
            }

            try
            {
                string[] parameters = query.Decrypt().Split('|');
                if (DateTime.Parse(parameters[0]).AddDays(1) < DateTime.Now)
                    SiteContext.RenderMessage(ExceptionType.PageNotFond, SiteUrls.Urls.Home);
            }
            catch
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError, SiteUrls.Urls.Home);
            }
        }

        #endregion
    }

    /// <summary>
    /// 
    /// </summary>
    public class UserSecurity
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">登录用户名</param>
        /// <param name="userPsw">登录密码</param>
        public static void Login(string userName, string userPsw)
        {
            UserInfo userInfo = Users.GetUser(userName);
            if (userInfo == null)
            {
                SiteContext.RenderMessage(ExceptionType.UserNotFound);
                return;
            }

            if (userInfo.Password == Globals.MD5(userPsw))
            {
                if (userInfo.Status == StatusType.Disabled)
                {
                    SiteContext.RenderMessage(ExceptionType.UserDisabled);
                }
                else if (userInfo.Status == StatusType.Deleted)
                {
                    SiteContext.RenderMessage(ExceptionType.UserDeleted);
                }
                else if (userInfo.Status == StatusType.Enabled)
                {
                    CreateFormsAuthentication(userName);

                    string url = SiteContext.Current.ReturnUrl;
                    if (string.IsNullOrEmpty(url))
                        url = userInfo.IsAdmin ? SiteUrls.Urls.AdminHome : SiteUrls.Urls.UserMyself();
                    
                    SiteContext.Redirect(url);
                }
                else
                {
                    SiteContext.RenderMessage(ExceptionType.UnknownError);
                }
            }
            else
            {
                SiteContext.RenderMessage(ExceptionType.UserPasswordError);
            }
        }
    

        /// <summary>
        /// 更换用户密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="oldPsw">老密码(当为管理员修改时，或通过url取回密码时可以为空。)</param>
        /// <param name="newPsw">新密码</param>
        public static void ChangePassword(string userName, string oldPsw, string newPsw)
        {
            bool label = (userName == SiteContext.Current.UserName);//当用户自己修改自己密码时缓存用户，当管理员修改用户密码时用户信息不缓存

            bool success = false;
            UserInfo info = Users.GetUser(userName);
            if (info == null)
            {
                SiteContext.RenderMessage(ExceptionType.UserNotFound);
                return;
            }

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (info.Password == Globals.MD5(oldPsw) || (SiteContext.Current.User.IsAdmin && !label))
                {
                    success = Users.ChangePassword(info.Id, newPsw);
                }
                else
                {
                    SiteContext.RenderMessage(ExceptionType.UserPasswordError);
                    return;
                }
            }
           
            if (success)
                SiteContext.RenderMessage(ExceptionType.UserPasswordChangeSuccess);
            else
                SiteContext.RenderMessage(ExceptionType.UnknownError);
        }

        /// <summary>
        /// 根据用户信息生成验证票
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="status"></param>
        public static void CreateFormsAuthentication(string userName)
        {
            FormsAuthentication.SetAuthCookie(userName,false);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
            
            SiteContext.Redirect(SiteUrls.Urls.Home);
        }
    }

   
}
